package org.onion.pattern.event.outbox.storage;

import org.apache.commons.lang3.StringUtils;
import org.onion.pattern.event.outbox.OutboxEventStorage;
import org.onion.pattern.event.outbox.data.OutboxEventInfo;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 内存实现的事件存储
 */
public class MemoryOutboxEventStorage implements OutboxEventStorage {

    private final Map<String, OutboxEventInfo> storage = new ConcurrentHashMap<>(200);

    @Override
    public List<OutboxEventInfo> findReadyEventByGroup(String group, int limit) {
        if (this.storage.isEmpty()) {
            return Collections.emptyList();
        }
        return this.storage.values().stream()
                .filter(x -> StringUtils.equals(group, x.getGroup()))
                .limit(limit).collect(Collectors.toList());
    }


    @Override
    public Optional<OutboxEventInfo> findByEventKey(String eventKey) {
        OutboxEventInfo outBoxEventInfo = this.storage.get(eventKey);
        return Optional.ofNullable(outBoxEventInfo);
    }

    @Override
    public void insert(OutboxEventInfo eventInfo) {
        storage.put(eventInfo.getEventKey(), eventInfo);
    }

    @Override
    public void batchInsert(List<OutboxEventInfo> eventInfo) {
        eventInfo.forEach(x -> storage.put(x.getEventKey(), x));
    }

    @Override
    public void ack(Set<String> eventKeys) {
        this.deleteByEventKey(eventKeys);
    }

    @Override
    public void deleteByEventKey(Set<String> eventKeys) {
        eventKeys.forEach(storage::remove);
    }

}
